<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { getListService, findByIdService, publishService, addNoticeService, deleteNoticeService, updateNoticeService } from '@/api/notice'

const drawer = ref(false)

const form = reactive({
    tittle: '',
    type: '',
    content: '',
    status: 1
})

const rules1 = {
    tittle: [
        { required: true, message: '标题不可为空！', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '类型不可为空！', trigger: 'blur' }
    ]
}

const quill = ref()

const clearForm = () => {
    form.tittle = ''
    form.type = ''
    form.content = ''
    form.status = 1
    quill.value.setText('')
}

const handleClose = () => {
    ElMessageBox.confirm(
        '是否保存到草稿?',
        'Info',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'info',
        }
    )
        .then(() => {
            toDraft()
        })
        .catch(() => {
            // form.value = {tittle: '',type: '',context: '',status: null}
            drawer.value = false
        })
}

const toDraft = async () => {
    form.status = 0
    await addNoticeService(form)
    ElMessage.success("草稿保存成功")
    drawer.value = false
    getList()
}

const submit = async () => {
    await addNoticeService(form)
    ElMessage.success("新增通知" + form.type + "成功")
    drawer.value = false
    getList()
}


const tableData = reactive([])

const search = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.tittle.toLowerCase().includes(search.value.toLowerCase())
    )
)

const pageNum = ref(1)
const total = ref(20)
const pageSize = ref(10)

async function getList() {
    tableData.length = 0
    let result = await getListService(pageNum.value, pageSize.value)
    total.value = result.data.total
    for (let i = 0; i < result.data.items.length; i++) {
        result.data.items[i].time = result.data.items[i].time.slice(0, 19)   //此处拿到的时间有毫秒值，直接用字符串切割
        tableData.push(result.data.items[i])
        // console.log(result.data.items[i].time)
    }
}
getList()

const onSizeChange = (size) => {
    pageSize.value = size
    getList()
}
const onCurrentChange = (num) => {
    pageNum.value = num
    getList()
}

const deleteNotice = async (id) => {
    await deleteNoticeService(id)
    ElMessage.success('删除成功')
    getList()
}

const publish = async (id) => {
    await publishService(id)
    ElMessage.success('发布成功')
    getList()
}


const drawer2 = ref(false)

const updateForm = reactive({
    id: null,
    tittle: '',
    type: '',
    content: '',
    // status: null
})

const handleEdit = async (id) => {
    let result = await findByIdService(id)
    // console.log(result)
    updateForm.id = id
    updateForm.tittle = result.data.tittle
    updateForm.type = result.data.type
    updateForm.content = result.data.content
    // updateForm.status = result.data.status
    drawer2.value = true
}

const save = async () => {
    await updateNoticeService(updateForm)
    ElMessage.success('更新成功')
    drawer2.value = false
}

const handleClose2 = () => {
    ElMessageBox.confirm(
        '是否需要保存此次修改?',
        'Info',
        {
            confirmButtonText: '保存',
            cancelButtonText: '取消',
            type: 'info',
        }
    )
        .then(() => {
            save()
        })
        .catch(() => {
            drawer2.value = false
        })
}

const detail = reactive({
    tittle: '',
    time: null,
    content: ''
})

const drawer3 = ref(false)
const showDetail = async (row) => {
    detail.tittle = row.tittle
    detail.time = row.time
    detail.content = (await findByIdService(row.id)).data.content
    drawer3.value = true
}


</script>



<template>
    <div style="padding-left: 50px;">
        <div style="display: flex;padding-top: 50px;">
            <el-input v-model="search" placeholder="搜索相关信息" style="width: 300px;" />
            <el-button type="primary" @click="drawer = true"
                style="width: 100px;padding: 18px;background-color: rgb(19, 179, 232);color: white;margin-left:95vh;">发布通知公告</el-button>
        </div>
        <el-table :data="filterTableData" border stripe style="min-width:100%;margin-top: 30px;">
            <el-table-column label="ID" prop="id" sortable />
            <el-table-column label="标题" prop="tittle" sortable>
                <template #default="scope">
                    <el-link type="primary" @click="showDetail(scope.row)">{{ scope.row.tittle }}</el-link>
                </template>
            </el-table-column>
            <el-table-column label="类型" prop="type" />
            <el-table-column label="更新时间" prop="time" />
            <el-table-column label="状态" prop="status">
                <template #default="scope">
                    <i v-if="scope.row.status === 0" style="color: lightgray;">草稿</i>
                    <i v-if="scope.row.status === 1" style="color: lightskyblue;">已发布</i>
                </template></el-table-column>
            <el-table-column label="操作" align="center" width='250px'>
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button style="background: lightblue;color: aliceblue;" v-if="scope.row.status === 1"
                        disabled>发布</el-button>
                    <el-button @click="publish(scope.row.id)" style="background: rgb(19, 179, 232);color: aliceblue;"
                        v-if="scope.row.status === 0">发布</el-button>
                    <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled" icon-color="red"
                        title="确认要删除此通知/公告吗？" @confirm="deleteNotice(scope.row.id)">
                        <template #reference>
                            <el-button type="danger">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0;">
            <el-pagination v-model:current-page="pageNum" v-model:page-size='pageSize' :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="onSizeChange"
                @current-change="onCurrentChange" />
        </div>
    </div>

    <el-drawer v-model="drawer" title="发布通知/公告" :before-close="handleClose" direction="rtl" size="50%"
        @open="clearForm">
        <div class="demo-drawer__content">
            <el-form :model="form" label-width="70px" :rules="rules1">
                <el-form-item label="标题" prop="tittle">
                    <el-input v-model="form.tittle" />
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择发布类型">
                        <el-option label="通知" value="通知" />
                        <el-option label="公告要闻" value="公告" />
                    </el-select>
                </el-form-item>
                <el-form-item label="正文">
                    <div class="editor" style="width: 100%;height: 400px;">
                        <quill-editor ref="quill" theme="snow" v-model:content="form.content"
                            contentType="html"></quill-editor>
                    </div>
                </el-form-item>
            </el-form>
            <div style="margin-left: 70px;padding-top: 60px;">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="warning" @click="toDraft">保存到草稿</el-button>
                <el-button type="primary" @click="submit">发布</el-button>
            </div>
        </div>
    </el-drawer>

    <el-drawer v-model="drawer2" title="编辑通知/公告" :before-close="handleClose2" direction="rtl" size="50%">
        <div class="demo-drawer__content">
            <el-form :model="updateForm" label-width="70px" :rules="rules1">
                <el-form-item label="标题" prop="tittle">
                    <el-input v-model="updateForm.tittle" />
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="updateForm.type" placeholder="请选择发布类型">
                        <el-option label="通知" value="通知" />
                        <el-option label="公告要闻" value="公告" />
                    </el-select>
                </el-form-item>
                <el-form-item label="正文">
                    <div class="editor" style="width: 100%;height: 400px;">
                        <quill-editor theme="snow" v-model:content="updateForm.content"
                            contentType="html"></quill-editor>
                    </div>
                </el-form-item>
            </el-form>
            <div style="margin-left: 70px;padding-top: 60px;">
                <el-button @click="drawer2 = false">取消</el-button>
                <!-- <el-button type="warning" @click="toDraft">保存到草稿</el-button> -->
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </div>
    </el-drawer>

    <el-drawer v-model="drawer3" title="详情" direction="ltr" size="75%">
        <div>
            <h1 style="text-align: center;padding: 20px;">{{ detail.tittle }}</h1>
            <p style="text-align: end;margin-right: 70px;color: gray;padding: 10px;">{{ detail.time }}</p>
            <div v-html="detail.content" style="padding: 20px;"></div>
        </div>
    </el-drawer>
</template>